package com.sunnada.edu.business.attendance.service;

import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

import com.sunnada.edu.system.pub.common.AppContext;
import com.sunnada.edu.system.pub.dao.PubDao;
import com.sunnada.edu.system.pub.util.Utils;

public class AttendanceMethods {
	static boolean absenteeism = false;
	static String dateStatus1 = "";
	static String dateStatus2 = "";

	public static int AttendanceStatistics(HashMap<String, String> params) {
		PubDao dao = AppContext.getInstance().getPubDao();
		Calendar calendar = Calendar.getInstance();//此时打印它获取的是系统当前时间
        calendar.add(Calendar.DATE, -1);    //得到前一天
        String  times = new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime());
        //先删除当天的数据
        AttendanceRecordDel(times);
        //-----------查询当天有多少人要打卡--------------------------
		String sql = "SELECT DISTINCT t.JOBNO FROM t_attend_worker t WHERE '"+times+"' >= t.BEG_TIME"
				+ " AND t.END_TIME >= '"+times+"'";
		List<?> l = dao.selectList(sql);
		for (int i = 0; i < l.size(); i++) {
			HashMap<String, String> param = (HashMap<String, String>) l.get(i);
			String jobno = param.get("JOBNO");
			//-----------通过人和日期获取打卡的时段--------------------------
			String sql1 = "SELECT t.ATTENCE_ID, t.JOBNO,t.BEG_TIME,t.END_TIME,t.SIGN_TIME,t.SIGNOUT_TIME,m.LATE_TMIE1,m.LATE_TMIE2, m.LATE_TMIE3,m.DEBIT_TYPE,m.START_TIME,"
					+ "m.TIMEBASE, t.SIGN_TIME2,t.SIGNOUT_TIME2 FROM t_attend_worker t,t_attendance m WHERE  t.ATTENCE_ID = m.ATTENCE_ID AND '"+times+"' >= t.BEG_TIME "
					+ " AND t.END_TIME >= '"+times+"' AND t.JOBNO = '"+jobno+"' ";
			List<?> l1 = dao.selectList(sql1);
			for (int j = 0; j < l1.size(); j++) {
				 HashMap<String, String> param1 = (HashMap<String, String>) l1.get(j);
				 String signTime = param1.get("SIGN_TIME");
				 String signoutTime = param1.get("SIGNOUT_TIME");
				 String signTime2 = param1.get("SIGN_TIME2");
				 String signoutTime2 = param1.get("SIGNOUT_TIME2");
				 int debitType = Integer.parseInt(param1.get("DEBIT_TYPE"));
				 String lateTmie1 = param1.get("LATE_TMIE1");
				 String lateTmie2 = param1.get("LATE_TMIE2");
				 String lateTmie3 = param1.get("LATE_TMIE3");
				 String startTime  = param1.get("START_TIME");
				 int timeBase = Integer.parseInt(param1.get("TIMEBASE"));
				 String jobId = param1.get("JOBNO");
				 String attenceId = param1.get("ATTENCE_ID");
				 //---------------------------------------------
				 String recId = UUID.randomUUID().toString();
				 String attenceTime = times;
				 String endTimes = "";
				 String workingHours = "0";
				 String attendanceMachine = "";
				 String dateStatus = "0";
                 String attendanceStatus= "0";
                 String num = "";
                 boolean islate = false;
                 
				//-----------通过打卡的时段去获取人的具体打卡时间--------------------------
				   DateFormat df2 = new SimpleDateFormat("HH:mm:ss");
				   String sql2 = "";
				//-----------首次签到打卡比较--------------------------
		    	   if(Utils.isNotNull(signTime)){
		    		   endTimes = Timecom(signTime,signoutTime);
		    		   num = "1";
		    		   sql2 = "";
		    		   sql2 +="(SELECT   t.JOBNO , DATE_FORMAT(MIN(t.SIGN_TIME),'%H:%i:%s') SIGN_TIME,t.MACHINE_CODE,t.PUNCH_TYPE,t.ADDRESS_CODE,";
				       sql2 +=" t.ADDRESS_NAME FROM t_attendance_app t  WHERE DATE_FORMAT(t.SIGN_TIME,'%Y-%m-%d') = '"+times+"' AND REC_STATUS IN('0','1') AND t.JOBNO = '"+jobno+"'";
				       sql2 +="AND  DATE_FORMAT(t.SIGN_TIME, '%H:%i:%s') >='"+startTime+"' AND '"+endTimes+"'>= DATE_FORMAT(t.SIGN_TIME, '%H:%i:%s')) "; 
				       List<?> l2 = dao.selectList(sql2);
				       islate=AttendanceAppMin(timeBase, l2, recId, num, signTime,signoutTime, debitType, lateTmie1,lateTmie2,lateTmie3, islate );
		    	   }
		    	 //-----------首次签退打卡比较--------------------------
		    	   if(Utils.isNotNull(signoutTime)){
		    		   startTime = endTimes;
		    		   num = "2";
		    		   sql2 = "";
		    		   sql2 +="SELECT   t.JOBNO , DATE_FORMAT(MAX(t.SIGN_TIME),'%H:%i:%s') SIGN_TIME,t.MACHINE_CODE,t.PUNCH_TYPE,t.ADDRESS_CODE,";
				       sql2 +=" t.ADDRESS_NAME FROM t_attendance_app t  WHERE DATE_FORMAT(t.SIGN_TIME,'%Y-%m-%d') = '"+times+"' AND REC_STATUS IN('0','1') AND t.JOBNO = '"+jobno+"'";
				       sql2 +="AND  DATE_FORMAT(t.SIGN_TIME, '%H:%i:%s') >'"+startTime+"'";
				       if(l1.size()==2){
				    	   HashMap<String, String> ll = null;
				    	   if(j==0){
				    		   ll=(HashMap<String, String>) l1.get(1);
				    	   }else{
				    		  ll= (HashMap<String, String>) l1.get(0);
				    	   }
				    	   try {
				    		   String s = ll.get("START_TIME");
								 Date sg1 = df2.parse(startTime);
								 Date ct1 = df2.parse(s);
								 if((ct1.getTime() - sg1.getTime())>=0 ){
							    	 endTimes = ll.get("START_TIME");
							    	 sql2 +="AND '"+endTimes+"'>= DATE_FORMAT(t.SIGN_TIME, '%H:%i:%s')";
							     }
				    	   } catch (ParseException e) {
							}
				       }
				       if(Utils.isNotNull(signTime2)){
				    	   endTimes = Timecom(signoutTime,signTime2);
				    	   sql2 +="AND '"+endTimes+"'>= DATE_FORMAT(t.SIGN_TIME, '%H:%i:%s')";
				       }
				       List<?> l2 = dao.selectList(sql2);
				       islate=AttendanceAppMax(timeBase, l2, recId, num, signTime,signoutTime, debitType, lateTmie1,lateTmie2,lateTmie3, islate );
		    	   } 
		    	   absenteeism = false;
		    	 //-----------二次签到打卡比较--------------------------
		    	   if(Utils.isNotNull(signTime2)){
		    		   startTime = endTimes;
		    		   endTimes = Timecom(signTime2,signoutTime2);
		    		   num = "3";
		    		   sql2 = "";
		    		   sql2 +="(SELECT   t.JOBNO , DATE_FORMAT(MIN(t.SIGN_TIME),'%H:%i:%s') SIGN_TIME,t.MACHINE_CODE,t.PUNCH_TYPE,t.ADDRESS_CODE,";
				       sql2 +=" t.ADDRESS_NAME FROM t_attendance_app t  WHERE DATE_FORMAT(t.SIGN_TIME,'%Y-%m-%d') = '"+times+"' AND REC_STATUS IN('0','1') AND t.JOBNO = '"+jobno+"'";
				       sql2 +="AND  DATE_FORMAT(t.SIGN_TIME, '%H:%i:%s') >'"+startTime+"' AND '"+endTimes+"'>= DATE_FORMAT(t.SIGN_TIME, '%H:%i:%s')) ";
				       List<?> l2 = dao.selectList(sql2);
				       islate=AttendanceAppMin(timeBase, l2, recId, num, signTime2,signoutTime2, debitType, lateTmie1,lateTmie2,lateTmie3, islate );
		    	   }
		    	 //-----------二次签退打卡比较--------------------------
		    	   if(Utils.isNotNull(signoutTime2)){
		    		   startTime = endTimes;
		    		   num = "4";
		    		   sql2 = "";
		    		   sql2 +="(SELECT   t.JOBNO , DATE_FORMAT(MAX(t.SIGN_TIME),'%H:%i:%s') SIGN_TIME,t.MACHINE_CODE,t.PUNCH_TYPE,t.ADDRESS_CODE,";
				       sql2 +=" t.ADDRESS_NAME FROM t_attendance_app t  WHERE DATE_FORMAT(t.SIGN_TIME,'%Y-%m-%d') = '"+times+"' AND REC_STATUS IN('0','1') AND t.JOBNO = '"+jobno+"'";
				       sql2 +="AND  DATE_FORMAT(t.SIGN_TIME, '%H:%i:%s') >'"+startTime+"')";
				       List<?> l2 = dao.selectList(sql2);
				       islate=AttendanceAppMax(timeBase, l2, recId, num,signTime2, signoutTime2, debitType, lateTmie1,lateTmie2,lateTmie3, islate );
		    	   }
		    	   if(islate == true){
		    		   attendanceStatus= "1";
		    	   }
					 
					try {
						 Date sg1 = df2.parse(signTime);
						 Date ct1 = df2.parse(signoutTime);
						 long diff1 = ct1.getTime() - sg1.getTime();
						 if(Utils.isNotNull(signTime2) && Utils.isNotNull(signoutTime2)){
							 sg1 = df2.parse(signTime2);
				    		 ct1 = df2.parse(signoutTime2);
				    		 diff1 +=(ct1.getTime() - sg1.getTime());
						 }
						 DecimalFormat def = new DecimalFormat("######0.0");   
						 workingHours = def.format((diff1/3600000.0));
					} catch (ParseException e) {
					}
		    				    	   
		    	   String sqladd2 = "";
		              sqladd2 +="insert into t_attendance_record (REC_ID, JOBNO,WORKING_HOURS,ATTENDANCE_MACHINE,";
		              sqladd2 +="DATE_STATUS, ATTENDANCE_STATUS, REC_STATUS,REC_PERSON, REC_TIME, REC_UPDATETIME,";
		              sqladd2 +="REC_UPDATEPERSON,ATTENCE_ID,ATTENCE_TIME) VALUES(";
		              sqladd2 +="'"+recId+"','"+jobId+"','"+workingHours+"','"+attendanceMachine+"','"+dateStatus+"','"+attendanceStatus+"',";
		              sqladd2 +="'0',null,now(),now(),null,'"+attenceId+"','"+attenceTime+"')";
		              dao.insert(sqladd2);
			}
		
		}
		
		return 1;
	}
	//获取两时间中间时间
	public static String Timecom(String signTime,String signoutTime){
		DateFormat df = new SimpleDateFormat("HH:mm:ss");
		String s ="";
		try
		{
		   Date d2 = df.parse(signTime);
	       Date d1 = df.parse(signoutTime);
	       long dif = d1.getTime() - d2.getTime();
	       d2.setSeconds((int) (d2.getSeconds()+(dif/2000)));
	       s = df.format(d2);
		}
		catch (Exception e)
		{
		}
		return s;
	}
	
	//获取两时间差
	public static String TimeDifference(String signTime,String signoutTime){
		DateFormat df = new SimpleDateFormat("HH:mm:ss");
		String s ="";
		try {
			 Date sg1 = df.parse(signTime);
			 Date ct1 = df.parse(signoutTime);
			 long diff1 = ct1.getTime() - sg1.getTime();
			 DecimalFormat def = new DecimalFormat("######0.00"); 
			 s = def.format((diff1/60000.0));
			 s = s.substring(0, s.indexOf("."));
		} catch (ParseException e) {
		}
		return s;
	}
	
	
	public static boolean AttendanceAppMin(int timeBase,List<?> l2,String recId,String num,String signTime,String signoutTime,int debitType,String lateTmie1,String lateTmie2,String lateTmie3,boolean islate ) {
		 DateFormat df2 = new SimpleDateFormat("HH:mm:ss");
		 String attendanceStatu= "";
		 String lateTime = "";
		 String amount = "";
		 String clockTime ="";
		if(l2.size()>0 && Utils.isNotNull(l2.get(0))){
	    	   HashMap<String, String> param2 = (HashMap<String, String>) l2.get(0); 
	    	    clockTime = param2.get("SIGN_TIME");
	    	   try
				{
	    		    Date sg = df2.parse(signTime);
	    		    Date ct = df2.parse(clockTime);
	    		    if((sg.getTime() - ct.getTime())>=0 ){
	    		    	   attendanceStatu = "1";
					}else{
						   long diff = ct.getTime() - sg.getTime();
						   if(Integer.parseInt(lateTmie1)>=(diff/60000)){
							   attendanceStatu = "1";
						   }else if(Integer.parseInt(lateTmie2)<(diff/60000) &&Integer.parseInt(lateTmie3)>(diff/60000)){
							   islate = true;
							   attendanceStatu = "2";
							   DecimalFormat    def   = new DecimalFormat("######0.00");   
							   lateTime = def.format((diff/60000.0))+"";
							   amount = def.format((diff/60000.0/timeBase)*debitType)+"";
							   lateTime = lateTime.substring(0, lateTime.indexOf("."));
							   amount = amount.substring(0, amount.indexOf("."));
						   }else{
							   lateTime = TimeDifference(signTime,signoutTime);
							   islate = true;
							   absenteeism = true;
					    	   attendanceStatu = "5";
						   }
					}
				}
				catch (Exception e)
				{
				}
	       }else{
	    	   islate = true;
	    	   attendanceStatu = "4";  
	       }
		 dateStatus1 = attendanceStatu; 
		 AttendanceRecordDataAdd(recId,num,signTime,clockTime,lateTime,attendanceStatu,amount);
		return islate;
	}
	
	public static boolean AttendanceAppMax(int timeBase,List<?> l2,String recId,String num,String signTime,String signoutTime,int debitType,String lateTmie1,String lateTmie2,String lateTmie3,boolean islate ) {
		DateFormat df2 = new SimpleDateFormat("HH:mm:ss");
		 String attendanceStatu= "";
		 String lateTime = "";
		 String amount = "";
		 String clockTime ="";
		if(l2.size()>0 && Utils.isNotNull(l2.get(0))){
	    	   HashMap<String, String> param2 = (HashMap<String, String>) l2.get(0); 
	    	    clockTime = param2.get("SIGN_TIME");
	    	   try
				{
	    		    Date sg = df2.parse(signoutTime);
	    		    Date ct = df2.parse(clockTime);
	    		    if((ct.getTime() - sg.getTime())>=0 ){
	    		    	   attendanceStatu = "1";
					}else{
						   long diff = sg.getTime() - ct.getTime();
						   if(Integer.parseInt(lateTmie1)>=(diff/60000)){
							   attendanceStatu = "1";
						   }else if(Integer.parseInt(lateTmie2)<(diff/60000) &&Integer.parseInt(lateTmie3)>(diff/60000)){
							   islate = true;
							   attendanceStatu = "3";
							   if(absenteeism){
								   lateTime = "0"; 
								   amount = "0";
							   }else{
								   DecimalFormat    def   = new DecimalFormat("######0.00");
								   lateTime = def.format((diff/60000.0))+"";
								   amount = def.format((diff/60000.0/timeBase)*debitType)+""; 
								   lateTime = lateTime.substring(0, lateTime.indexOf("."));
								   amount = amount.substring(0, amount.indexOf("."));
							   }
						   }else{
							   if(absenteeism){
								   lateTime = "0"; 
							   }else{
								   lateTime = TimeDifference(signTime,signoutTime); 
							   }
							   islate = true;
					    	   attendanceStatu = "5";  
						   }
					}
				}
				catch (Exception e)
				{
				}
	    
	       }else{
	    	   islate = true;
	    	   attendanceStatu = "4";
	       }
		
		if(dateStatus1.equals("2")|| dateStatus1.equals("3")){
			if(attendanceStatu.equals("5")){
				AttendanceUpdate(recId,num);
			}
		}
	       AttendanceRecordDataAdd(recId,num,signoutTime,clockTime,lateTime,attendanceStatu,amount);
			return islate;
		}
	
	public static int AttendanceRecordDataAdd(String recId,String num,String signTime,String clockTime,String lateTime, String attendanceStatu,String amount ) {
		PubDao dao = AppContext.getInstance().getPubDao();
		String sqladd1 = "";
        sqladd1 +="INSERT INTO t_attendance_record_data ( REC_ID,NUM,SIGN_TIME,";
        sqladd1 +="CLOCK_TIME,LATE_TIME,ATTENDANCE_STATUS,AMOUNT) VALUES(";
        sqladd1 +="'"+recId+"','"+num+"','"+signTime+"','"+clockTime+"','"+lateTime+"','"+attendanceStatu+"','"+amount+"')";
        dao.insert(sqladd1);
		return 1;
	}
	
	
	
	public static int AttendanceUpdate(String recId,String num) {
		if(num.equals("2")){
			num ="1";
		}
		if(num.equals("4")){
			num ="3";
		}
		PubDao dao = AppContext.getInstance().getPubDao();
		String sqladd2 = "";
		sqladd2 +="UPDATE t_attendance_record_data  SET LATE_TIME = '0',AMOUNT = '0' WHERE REC_ID = '"+recId+"' AND NUM = '"+num+"' ";
		dao.update(sqladd2);
		return 1;
	}
	
	
	//删除考勤数据
	public static int AttendanceRecordDel(String times) {
		PubDao dao = AppContext.getInstance().getPubDao();
		String sqladd1 = "";
		String sqladd2 = "";
		String sql2 = "";
		   sql2 +="SELECT GROUP_CONCAT(t.REC_ID) REC_ID FROM t_attendance_record t ";
	       sql2 +="WHERE DATE_FORMAT(t.ATTENCE_TIME, '%Y-%m-%d') = '"+times+"'";
	       List<?> l = dao.selectList(sql2);
		if(l.size()>0 && Utils.isNotNull(l.get(0))){
			sqladd2 +="DELETE FROM t_attendance_record_data WHERE REC_ID in(SELECT DISTINCT t.REC_ID FROM t_attendance_record t WHERE";
			sqladd2 +=" DATE_FORMAT(t.ATTENCE_TIME, '%Y-%m-%d') = '"+times+"')";
			int d =dao.delete(sqladd2);
			sqladd1 +="DELETE FROM t_attendance_record WHERE REC_ID in( select a.REC_ID from (SELECT DISTINCT t.REC_ID FROM t_attendance_record t WHERE";
			sqladd1 +=" DATE_FORMAT(t.ATTENCE_TIME, '%Y-%m-%d') = '"+times+"') a)";
			int s =dao.delete(sqladd1);
			
		}
		return 1;
	}
	
	
	//删除工人对应的考勤关系表
	public static int AttendanceDel(String l) {
		PubDao dao = AppContext.getInstance().getPubDao();
		if(Utils.isNotNull(l)){
			String sqladd1 = "";
			String sqladd2 = "";
			sqladd1 +="DELETE FROM t_attend_worker WHERE JOBNO in("+Utils.getSqlSplitStr(l)+")";
			dao.delete(sqladd1);
			sqladd2 +="UPDATE t_attendance_record  SET REC_STATUS = '2' WHERE JOBNO in("+Utils.getSqlSplitStr(l)+")";
			dao.update(sqladd2);
		}
		return 1;
	}
	
	
	//考勤统计修改
	public static int AttendanceRecordDataUpdate(String recId,String num,String status ,String lateTime,String amount,String clockTime) {
		PubDao dao = AppContext.getInstance().getPubDao();
		String sqladd2 = "";
		sqladd2 +="UPDATE t_attendance_record_data  SET ATTENDANCE_STATUS = '"+status+"', ";
		sqladd2 +="LATE_TIME='"+lateTime+"',AMOUNT='"+amount+"',CLOCK_TIME='"+clockTime+"' WHERE REC_ID ='"+recId+"' and NUM ='"+num+"' ";
		dao.update(sqladd2);
		return 1;
	}
	
	//考勤统计修改
	public static int AttendanceRecordUpdate(String recId,String status ) {
		PubDao dao = AppContext.getInstance().getPubDao();
		String sqladd1 = "";
		sqladd1 +="UPDATE t_attendance_record  SET DATE_STATUS = '1' ,ATTENDANCE_STATUS='"+status+"' WHERE REC_ID ='"+recId+"'";
		dao.update(sqladd1);
		return 1;
	}
	

}
